<?php
include_once("../service/productService.php");
include_once("../service/categoryService.php");
include_once("../util/constant.php");

$proId = $_POST["proId"];
$disId = $_POST["discount"];
$name = $_POST["name"];
$code = $_POST["code"];
$visibility = $_POST["visibility"];
$status = $_POST["status"];
$price = $_POST["price"];
$description = $_POST["description"];
$attributes = isset($_POST["attributes"]) ? array_values($_POST["attributes"]) : "";
$attributeIds = isset($_POST["attIds"]) ? array_values($_POST["attIds"]) : "";
$optionalPrices = isset($_POST["optionalPrices"]) ? array_values($_POST["optionalPrices"]) : "";
$optionalPriceIds = isset($_POST["oppIds"]) ? array_values($_POST["oppIds"]) : "";

if(isset($name) && isset($code) && isset($visibility) && isset($price)){
    $result = updateProduct($disId, $status, $code, $name, $visibility, $price, $description, $proId);
}else{
    echo "<script>window.location.href = '../admin/product-detail.php?action='".NEW_ACTION.";</script>";
}
    
// check if the product has attributes and attributes' ids or not
if(!(empty($attributes) || 
	 empty($attributeIds) || 
	(count($attributes) != count($attributeIds)))){
	for($i = 0; $i < count($attributes); $i++){
		if(createAttributeValue(findCategoryByAttribute($attributeIds[$i]), $attributeIds[$i], $proId, $i, $attributes[$i]) < 0){
			updateAttributeValue(findCategoryByAttribute($attributeIds[$i]), $attributeIds[$i], $proId, $i, $attributes[$i]);
		}
	}
}

// check if the product has optional prices and optional prices' ids or not
/*if(!(empty($optionalPrices) || 
	 empty($optionalPriceIds) || 
	(count($optionalPrices) != count($optionalPriceIds)))){
   for($i = 0; $i < count($optionalPrices); $i++){
		if(createOptionalValue(findCategoryByOptionalPrice($optionalPriceIds[$i]), $optionalPriceIds[$i], $proId, $optionalPrices[$i]) < 0){
			updateOptionalValue(findCategoryByOptionalPrice($optionalPriceIds[$i]), $optionalPriceIds[$i], $proId, $optionalPrices[$i]);
		}          
   }
}
*/
echo "<script>window.location.href = '../admin/product-detail.php?action=".UPDATE_SUCCESSFULLY."&id=".$proId."';</script>";
?>